package de.ret_world.openrpgstudio.mapeditor.scripts;

import de.ret_world.openrpgstudio.editor.Database;
import de.ret_world.openrpgstudio.editor.Project;
import org.luaj.vm2.LuaValue;
import org.luaj.vm2.lib.TwoArgFunction;

/**
 * The TileSet Lua Library for working with TileSets through Lua code.
 *
 * @author Emu
 */
public class TileSetLib extends TwoArgFunction {

    @Override
    public LuaValue call(LuaValue arg1, LuaValue arg2) {
        Database database = Project.getInstance().getDatabase();
        switch (opcode) {
            case 0: {
                LuaValue t = tableOf();
                this.bind(t, TileSetLib.class, new String[]{"newTileset", "changeTileset", "getTileset"}, 1);
                env.set("Tilesets", t);
                return t;
            }
            case 1: //newTileSet
                if (arg1.istable()) {
                    TileSet ts = new TileSet();
                    ts.create(arg1);
                    database.putScriptObject(TileSet.TYPE, ts.getID(), ts);
                } else {
                    return error("no table: " + arg1);
                }
                return NIL;
            case 2: //changeTileSet
                if (arg1.isstring()) {
                    TileSet ts = (TileSet) database.getScriptObject(TileSet.TYPE, arg1.toString());
                    if (ts == null) {
                        return error("no such Tileset found unter: " + arg1);
                    }
                    if (arg2.istable()) {
                        ts.create(arg2);
                    } else {
                        return error("no table: " + arg2);
                    }
                } else {
                    return error("no string: " + arg1);
                }
                return NIL;
            case 3: //ngetTileSet
                if (arg1.isstring()) {
                    TileSet ts = (TileSet) database.getScriptObject(TileSet.TYPE, arg1.toString());
                    if (ts == null) {
                        return error("no such Tileset found unter: " + arg1);
                    } else {
                        return ts.toLua();
                    }
                }
                return NIL;
            default:
                return error("bad opcode: " + opcode);
        }
    }
}
